if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SaveRefCode]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SaveRefCode]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/******************************************************************
* Name:			SaveRefCode
* Purpose:		Saves a RefCode if it does not already exist
*
* PARAMETERS
* Name    		Description					
* -------------  	-------------------------------------------
*  @refDomain		Domain to which the code belongs
*  @refCode		The actual code
*  @refMeaning		Description of the code
*  @active		Status of the RefCode
******************************************************************/

CREATE Procedure [dbo].[SaveRefCode] (
		@refDomain		varchar(50),
		@refCode		varchar(100),
		@refMeaning		Varchar(2048),
		@active			char(1) 
)
AS
BEGIN

	SET NOCOUNT ON

	
	IF Exists(Select RefCode from Refcode where refcode = @refcode and refdomain = @refdomain)
	BEGIN
		UPDATE refcode 
		SET refMeaning	= @refMeaning,
			[active] = @active
		where refcode = @refcode and refdomain = @refdomain
	
		IF @@ERROR <> 0 GOTO ERROR_HANDLER
	END
	ELSE
	BEGIN
		INSERT INTO refcode (	
					refdomain,
					refcode,
					refmeaning,
					active)
				Values
				(	@refDomain,
					@refCode,
					@refMeaning,
					@active)
		
		IF @@ERROR <> 0 GOTO ERROR_HANDLER
	END	

	RETURN

	ERROR_HANDLER:
		RAISERROR('Unable to Save Refcode', 16, 1)
		RETURN
		
END

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF   